"""
工具函数模块
"""
from typing import Dict, Any
from datetime import datetime


def format_stock_info(info: Dict[str, Any], symbol: str) -> Dict[str, Any]:
    """
    格式化股票基本信息

    Args:
        info: 股票信息字典
        symbol: 股票代码

    Returns:
        格式化后的股票信息
    """
    return {
        'symbol': symbol,
        'name': info.get('longName', ''),
        'current_price': info.get('currentPrice', 0),
        'previous_close': info.get('previousClose', 0),
        'open': info.get('open', 0),
        'day_high': info.get('dayHigh', 0),
        'day_low': info.get('dayLow', 0),
        'volume': info.get('volume', 0),
        'market_cap': info.get('marketCap', 0),
        'currency': info.get('currency', 'USD'),
        'last_updated': datetime.now().isoformat()
    }


def format_financial_metrics(info: Dict[str, Any], symbol: str) -> Dict[str, Any]:
    """
    格式化财务指标

    Args:
        info: 股票信息字典
        symbol: 股票代码

    Returns:
        格式化后的财务指标
    """
    return {
        'symbol': symbol,
        'pe_ratio': info.get('trailingPE', 0),
        'pb_ratio': info.get('priceToBook', 0),
        'roe': info.get('returnOnEquity', 0),
        'dividend_yield': info.get('dividendYield', 0),
        'eps': info.get('trailingEps', 0),
        'revenue': info.get('totalRevenue', 0),
        'debt_to_equity': info.get('debtToEquity', 0),
        'profit_margin': info.get('profitMargins', 0),
        'operating_margin': info.get('operatingMargins', 0),
        'last_updated': datetime.now().isoformat()
    }


def build_analysis_data_dict(symbol: str, info: Dict[str, Any]) -> Dict[str, Any]:
    """
    构建AI分析用的数据字典

    Args:
        symbol: 股票代码
        info: 股票基本信息

    Returns:
        分析数据字典
    """
    from services.data_service import DataService

    return {
        'symbol': DataService.safe_string(symbol),
        'company_name': DataService.safe_string(info.get('longName', '')),
        'current_price': DataService.safe_float(info.get('currentPrice')),
        'previous_close': DataService.safe_float(info.get('previousClose')),
        'day_change': round(((DataService.safe_float(info.get('currentPrice')) - DataService.safe_float(info.get('previousClose'))) / max(DataService.safe_float(info.get('previousClose')), 1)) * 100, 2),
        'volume': DataService.safe_float(info.get('volume')),
        'market_cap': DataService.safe_float(info.get('marketCap')),
        'pe_ratio': DataService.safe_float(info.get('trailingPE')),
        'pb_ratio': DataService.safe_float(info.get('priceToBook')),
        'roe': DataService.safe_float(info.get('returnOnEquity')),
        'dividend_yield': DataService.safe_float(info.get('dividendYield')),
        'eps': DataService.safe_float(info.get('trailingEps')),
        'revenue': DataService.safe_float(info.get('totalRevenue')),
        'debt_to_equity': DataService.safe_float(info.get('debtToEquity')),
        'profit_margin': DataService.safe_float(info.get('profitMargins')),
        'operating_margin': DataService.safe_float(info.get('operatingMargins')),
        'sector': DataService.safe_string(info.get('sector', '')),
        'industry': DataService.safe_string(info.get('industry', '')),
        'business_summary': DataService.safe_string(info.get('longBusinessSummary', '')),
        '52_week_high': DataService.safe_float(info.get('fiftyTwoWeekHigh')),
        '52_week_low': DataService.safe_float(info.get('fiftyTwoWeekLow')),
        'analyst_rating': DataService.safe_string(info.get('recommendationKey', '')),
        'target_price': DataService.safe_float(info.get('targetMeanPrice')),
    }


def add_technical_indicators_to_analysis(analysis_data: Dict[str, Any], stock_data) -> Dict[str, Any]:
    """
    向分析数据添加技术指标

    Args:
        analysis_data: 分析数据字典
        stock_data: 股票历史数据

    Returns:
        包含技术指标的分析数据
    """
    import pandas as pd
    import numpy as np
    from services.data_service import DataService

    if not stock_data.empty:
        try:
            stock_data = stock_data.copy()
            stock_data['Daily_Return'] = stock_data['Close'].pct_change()
            daily_return_std = stock_data['Daily_Return'].std()
            volatility = float(daily_return_std) * np.sqrt(252)

            # 计算20日和50日移动平均线
            stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean()
            stock_data['MA50'] = stock_data['Close'].rolling(window=50).mean()

            close_last = stock_data['Close'].iloc[-1]
            current_price = float(close_last.item() if hasattr(close_last, 'item') else close_last)
            ma20_val = stock_data['MA20'].iloc[-1]
            ma50_val = stock_data['MA50'].iloc[-1]
            ma20 = float(ma20_val) if pd.notna(ma20_val) else 0
            ma50 = float(ma50_val) if pd.notna(ma50_val) else 0

            # 计算RSI (14日)
            delta = stock_data['Close'].diff()
            gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
            loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()

            try:
                with np.errstate(divide='ignore', invalid='ignore'):
                    rs_val = gain / loss
                    rs_val = rs_val.replace([np.inf, -np.inf], np.nan).fillna(1)

                rsi_val = rs_val.iloc[-1] if pd.notna(rs_val.iloc[-1]) else 1
                rsi = float(100 - (100 / (1 + rsi_val)))
            except Exception as e:
                print(f"RSI calculation handled: {e}")
                rsi = 50

            analysis_data.update({
                'volatility': round(volatility * 100, 2),
                'current_price_tech': current_price,
                'ma20': round(ma20, 2),
                'ma50': round(ma50, 2),
                'rsi': round(rsi, 2),
                'price_vs_ma20': round(((current_price - ma20) / ma20) * 100, 2) if ma20 > 0 else 0,
                'price_vs_ma50': round(((current_price - ma50) / ma50) * 100, 2) if ma50 > 0 else 0,
            })
        except Exception as e:
            print(f"技术指标计算错误: {e}")
            analysis_data.update({
                'volatility': 0,
                'current_price_tech': analysis_data.get('current_price', 0),
                'ma20': 0,
                'ma50': 0,
                'rsi': 50,
                'price_vs_ma20': 0,
                'price_vs_ma50': 0,
            })

    return analysis_data


def build_comprehensive_analysis_data(symbol: str, info: Dict[str, Any], stock_data, question: str = '', analysis_type: str = 'comprehensive', conversation_history: list = None) -> Dict[str, Any]:
    """
    构建完整的AI分析数据

    Args:
        symbol: 股票代码
        info: 股票基本信息
        stock_data: 股票历史数据
        question: 用户问题
        analysis_type: 分析类型
        conversation_history: 对话历史

    Returns:
        完整的分析数据字典
    """
    from services.data_service import DataService
    from services.technical_analysis import TechnicalAnalysis

    # 基础分析数据
    analysis_data = {
        'symbol': DataService.safe_string(symbol),
        'company_name': DataService.safe_string(info.get('longName', '')),
        'current_price': DataService.safe_float(info.get('currentPrice')),
        'previous_close': DataService.safe_float(info.get('previousClose')),
        'day_change': round(((DataService.safe_float(info.get('currentPrice')) - DataService.safe_float(info.get('previousClose'))) / max(DataService.safe_float(info.get('previousClose')), 1)) * 100, 2),
        'day_high': DataService.safe_float(info.get('dayHigh')),
        'day_low': DataService.safe_float(info.get('dayLow')),
        'volume': DataService.safe_float(info.get('volume')),
        'average_volume': DataService.safe_float(info.get('averageVolume')),
        'market_cap': DataService.safe_float(info.get('marketCap')),
        'enterprise_value': DataService.safe_float(info.get('enterpriseValue')),

        # 估值指标
        'pe_ratio': DataService.safe_float(info.get('trailingPE')),
        'forward_pe': DataService.safe_float(info.get('forwardPE')),
        'pb_ratio': DataService.safe_float(info.get('priceToBook')),
        'price_to_sales': DataService.safe_float(info.get('priceToSalesTrailing12Months')),
        'ev_to_revenue': DataService.safe_float(info.get('enterpriseToRevenue')),
        'ev_to_ebitda': DataService.safe_float(info.get('enterpriseToEbitda')),
        'peg_ratio': DataService.safe_float(info.get('trailingPegRatio')),

        # 盈利能力指标
        'roe': DataService.safe_float(info.get('returnOnEquity')),
        'roa': DataService.safe_float(info.get('returnOnAssets')),
        'profit_margins': DataService.safe_float(info.get('profitMargins')),
        'gross_margins': DataService.safe_float(info.get('grossMargins')),
        'operating_margins': DataService.safe_float(info.get('operatingMargins')),
        'ebitda_margins': DataService.safe_float(info.get('ebitdaMargins')),

        # 成长性指标
        'revenue_growth': DataService.safe_float(info.get('revenueGrowth')),
        'earnings_growth': DataService.safe_float(info.get('earningsGrowth')),
        'earnings_quarterly_growth': DataService.safe_float(info.get('earningsQuarterlyGrowth')),

        # 财务健康指标
        'dividend_yield': DataService.safe_float(info.get('dividendYield')),
        'dividend_rate': DataService.safe_float(info.get('dividendRate')),
        'payout_ratio': DataService.safe_float(info.get('payoutRatio')),
        'debt_to_equity': DataService.safe_float(info.get('debtToEquity')),
        'current_ratio': DataService.safe_float(info.get('currentRatio')),
        'quick_ratio': DataService.safe_float(info.get('quickRatio')),
        'beta': DataService.safe_float(info.get('beta')),

        # 现金流指标
        'free_cashflow': DataService.safe_float(info.get('freeCashflow')),
        'operating_cashflow': DataService.safe_float(info.get('operatingCashflow')),
        'total_cash': DataService.safe_float(info.get('totalCash')),
        'total_debt': DataService.safe_float(info.get('totalDebt')),

        # 股价技术指标
        '52_week_high': DataService.safe_float(info.get('fiftyTwoWeekHigh')),
        '52_week_low': DataService.safe_float(info.get('fiftyTwoWeekLow')),
        '50_day_average': DataService.safe_float(info.get('fiftyDayAverage')),
        '200_day_average': DataService.safe_float(info.get('twoHundredDayAverage')),

        # 分析师预期
        'target_mean_price': DataService.safe_float(info.get('targetMeanPrice')),
        'target_high_price': DataService.safe_float(info.get('targetHighPrice')),
        'target_low_price': DataService.safe_float(info.get('targetLowPrice')),
        'recommendation_mean': DataService.safe_float(info.get('recommendationMean')),
        'number_of_analysts': DataService.safe_float(info.get('numberOfAnalystOpinions')),

        # 公司基本信息
        'sector': DataService.safe_string(info.get('sector', '')),
        'industry': DataService.safe_string(info.get('industry', '')),
        'full_time_employees': DataService.safe_float(info.get('fullTimeEmployees')),
        'website': DataService.safe_string(info.get('website', '')),
        'business_summary': DataService.safe_string(info.get('longBusinessSummary', '')),

        # 其他重要指标
        'book_value': DataService.safe_float(info.get('bookValue')),
        'total_revenue': DataService.safe_float(info.get('totalRevenue')),
        'net_income': DataService.safe_float(info.get('netIncomeToCommon')),
        'trailing_eps': DataService.safe_float(info.get('trailingEps')),
        'forward_eps': DataService.safe_float(info.get('forwardEps')),
        'shares_outstanding': DataService.safe_float(info.get('sharesOutstanding')),
        'held_percent_institutions': DataService.safe_float(info.get('heldPercentInstitutions')),
        'held_percent_insiders': DataService.safe_float(info.get('heldPercentInsiders')),
        'short_percent_of_float': DataService.safe_float(info.get('shortPercentOfFloat')),

        # 风险指标
        'overall_risk': DataService.safe_float(info.get('overallRisk')),
        'audit_risk': DataService.safe_float(info.get('auditRisk')),
        'board_risk': DataService.safe_float(info.get('boardRisk')),
        'compensation_risk': DataService.safe_float(info.get('compensationRisk')),
        'share_holder_rights_risk': DataService.safe_float(info.get('shareHolderRightsRisk'))
    }

    # 添加技术指标数据
    technical_indicators = TechnicalAnalysis.calculate_technical_indicators(stock_data)
    analysis_data.update(technical_indicators)

    # 添加用户问题和分析类型
    analysis_data['user_question'] = question
    analysis_data['analysis_type'] = analysis_type
    analysis_data['conversation_history'] = conversation_history or []

    return analysis_data